package com.stackfarm.fvcommon.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.stackfarm.fvcommon.constant.SystemConstant;
import com.stackfarm.fvcommon.exception.UnhandledException;
import org.springframework.http.HttpStatus;

import java.util.Date;

public class JwtUtil {
    public static String generateToken(String username,String password){
        Algorithm algorithm=Algorithm.HMAC256(password);
        Date date=new Date();
        date.setTime(System.currentTimeMillis()+ SystemConstant.TOKEN_EXPIRE_TIME*1000*3600);
        String token= JWT.create().withClaim("username",username).withExpiresAt(date).sign(algorithm);
        return token;
    }
    public static String getUserName(String token) throws UnhandledException {
        if (token == null) {
            throw new UnhandledException(HttpStatus.BAD_REQUEST.value(),
                    "令牌不可为空",
                    BaseUtil.getRunLocation(Thread.currentThread().getStackTrace()[1]),
                    new Date());
        }
        String username;
        try {
            username = JWT.decode(token).getClaim("username").asString();
        } catch (JWTDecodeException e) {
            throw new UnhandledException(462,
                    "验证令牌有误 或令牌已过期",
                    BaseUtil.getRunLocation(Thread.currentThread().getStackTrace()[1]),
                    new Date());
        }
        return username;
    }
}
